package la.renzhen.rtpt.admin.boot.starter.redis;

import la.renzhen.rtpt.admin.boot.conditional.ConditionalOnPrefixProperty;
import la.renzhen.rtpt.admin.boot.starter.CenterServerAutoConfigruation;
import la.renzhen.rtpt.admin.source.CenterConfigurationSource;
import la.renzhen.rtpt.admin.source.redis.RedisCenterConfigurationSource;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.net.UnknownHostException;

/**
 * <p>
 *
 * @author <a href="mailto:zhouhaichao@2008.sina.com">haiker</a>
 * @version 16/05/2018 7:33 PM
 */
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
@AutoConfigureBefore(RedisProperties.class)
@ConditionalOnMissingBean(CenterServerAutoConfigruation.class)
@ConditionalOnPrefixProperty("rtpt.admin.redis")
public class RedisSourceAutoConfiguration {

    @Bean
    public Jedis jedisContent(RedisProperties config) {
        String host = config.getHost();
        int port = config.getPort();
        if (StringUtils.hasText(config.getUrl())) {
            HostAndPort hostAndPort = HostAndPort.parseString(config.getUrl());
            host = config.getHost();
            port = config.getPort();
        }
        int timeout = config.getTimeout();

        JedisPool pool = new JedisPool(jedisPoolConfig(config.getPool()), host, port, timeout);
        Jedis jedis = new Jedis();
        jedis.select(config.getDatabase());
        jedis.setDataSource(pool);

        String passwd = config.getPassword();
        if (StringUtils.hasText(passwd)) {
            Assert.isTrue(jedis.auth(passwd).equalsIgnoreCase("OK"), "redis auth password is invalid");
        }
        return jedis;
    }

    @Bean
    public CenterConfigurationSource redisSource(Jedis jedis, RedisProperties config) throws UnknownHostException {
        return new RedisCenterConfigurationSource(jedis, config.getModule());
    }

    private JedisPoolConfig jedisPoolConfig(RedisProperties.Pool poolConfig) {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(poolConfig.getMaxActive());
        config.setMaxIdle(poolConfig.getMaxIdle());
        config.setMinIdle(poolConfig.getMinIdle());
        config.setMaxWaitMillis(poolConfig.getMaxWait());
        return config;
    }

}
